"""
这里是几种socket通信的展示，TCP、UDP和广播。
tcp和udp的区别：tcp连接发送数据不能一个个发送，而udp可以将数据一个个的发送给服务器。
"""
import socket
import threading


class TCPServer:
    """ TCP服务器端接收数据。 """

    def __init__(self, ip, port):
        self.s = socket.socket()
        self.s.bind((ip, port))
        self.s.listen(0)
        t = threading.Thread(target=self.receive)
        t.start()

    def receive(self):
        print('receiving..')
        while 1:
            conn, addr = self.s.accept()        # 获取客户端的请求
            data = conn.recv(1024)              # 接收客户端的数据
            print(data.decode())


class UDPServer:
    """ UDP服务器端接收。"""

    def __init__(self, ip, port):
        self.s = socket.socket(type=socket.SOCK_DGRAM)
        self.s.bind((ip, port))
        t = threading.Thread(target=self.receive)
        t.start()

    def receive(self):
        while 1:
            data, addr = self.s.recvfrom(65535)
            print(data)
            self.s.sendto(b'no hi', addr)


class BroadcastServer:
    """ 广播服务器端接收。"""

    def __init__(self, port, info):
        self.info = info
        ip = '255.255.255.255'
        # ip = '<broadcast>'                      # 同上.
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.s.bind((ip, self.port))
        t = threading.Thread(target=self.receive)
        t.start()

    def receive(self):
        while True:
            data, addr = self.s.recvfrom(1024)
            # self.s.sendto(self.info.encode(), addr)
            print(data.decode(), addr)
            return data, addr
